<template>
  <view class="following-container">
    <!-- 标签页导航 -->
    <view class="tab-navigation">
      <view 
        class="tab-item"
        :class="{ active: currentTab === 'following' }"
        @click="switchTab('following')"
      >
        <text class="tab-text">关注 {{ followingCount }}</text>
      </view>
      <view 
        class="tab-item"
        :class="{ active: currentTab === 'followers' }"
        @click="switchTab('followers')"
      >
        <text class="tab-text">粉丝 {{ followersCount }}</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view 
      class="content-area" 
      scroll-y 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 关注列表 -->
      <view class="user-list" v-if="currentTab === 'following'">
        <view 
          class="user-item modern-card"
          v-for="user in followingList" 
          :key="user.uid"
        >
          <view class="user-info" @click="handleUserProfile(user)">
            <u-avatar 
              :src="user.avatar" 
              size="50"
              class="user-avatar"
            ></u-avatar>
            <view class="user-details">
              <text class="username">{{ user.username }}</text>
              <text class="user-desc" v-if="user.description">{{ user.description }}</text>
              <view class="user-stats">
                <text class="stat-text">{{ user.followersCount || 0 }} 粉丝</text>
                <text class="stat-text">{{ user.postCount || 0 }} 帖子</text>
              </view>
            </view>
          </view>
          
          <view class="user-actions">
            <u-button 
              v-if="user.isMutualFollow"
              type="info"
              size="small"
              plain
              @click="handleUnfollow(user)"
            >
              互相关注
            </u-button>
            <u-button 
              v-else
              type="info"
              size="small"
              plain
              @click="handleUnfollow(user)"
            >
              已关注
            </u-button>
          </view>
        </view>
      </view>

      <!-- 粉丝列表 -->
      <view class="user-list" v-if="currentTab === 'followers'">
        <view 
          class="user-item modern-card"
          v-for="user in followersList" 
          :key="user.uid"
        >
          <view class="user-info" @click="handleUserProfile(user)">
            <u-avatar 
              :src="user.avatar" 
              size="50"
              class="user-avatar"
            ></u-avatar>
            <view class="user-details">
              <text class="username">{{ user.username }}</text>
              <text class="user-desc" v-if="user.description">{{ user.description }}</text>
              <view class="user-stats">
                <text class="stat-text">{{ user.followersCount || 0 }} 粉丝</text>
                <text class="stat-text">{{ user.postCount || 0 }} 帖子</text>
              </view>
            </view>
          </view>
          
          <view class="user-actions">
            <u-button 
              v-if="user.isFollowed"
              type="info"
              size="small"
              plain
              @click="handleUnfollow(user)"
            >
              {{ user.isMutualFollow ? '互相关注' : '已关注' }}
            </u-button>
            <u-button 
              v-else
              type="primary"
              size="small"
              :custom-style="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none' }"
              @click="handleFollow(user)"
            >
              + 关注
            </u-button>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <u-loading-icon v-if="loading" color="#667eea" size="20"></u-loading-icon>
        <text class="load-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && getCurrentList().length === 0">
        <u-icon name="account" color="#ccc" size="60"></u-icon>
        <text class="empty-text">{{ getEmptyText() }}</text>
      </view>
    </scroll-view>

    <!-- Toast提示 -->
    
  </view>
</template>

<script>
export default {
  data() {
    return {
      uid: '',
      currentTab: 'following',
      refreshing: false,
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 20,
      
      // 统计数据
      followingCount: 0,
      followersCount: 0,
      
      // 列表数据
      followingList: [],
      followersList: []
    }
  },
  
  onLoad(options) {
    this.uid = options.uid || uni.getStorageSync('currentUserId') || '1001'
    this.initPage()
  },
  
  methods: {
    // 初始化页面
    async initPage() {
      await this.loadCounts()
      await this.loadCurrentTabData()
    },
    
    // 加载统计数据
    async loadCounts() {
      try {
        // 这里应该调用API获取统计数据
        // const res = await this.$api.getUserCounts(this.uid)
        
        // 模拟数据
        this.followingCount = Math.floor(Math.random() * 200) + 50
        this.followersCount = Math.floor(Math.random() * 500) + 100
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },
    
    // 切换标签页
    switchTab(tab) {
      this.currentTab = tab
      this.page = 1
      this.loadCurrentTabData()
    },
    
    // 加载当前标签页数据
    async loadCurrentTabData() {
      if (this.currentTab === 'following') {
        await this.loadFollowing()
      } else {
        await this.loadFollowers()
      }
    },
    
    // 加载关注列表
    async loadFollowing() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        // 这里应该调用API获取关注列表
        // const res = await this.$api.getFollowing({
        //   uid: this.uid,
        //   page: this.page,
        //   pageSize: this.pageSize
        // })
        
        // 模拟数据
        const mockUsers = this.generateMockUsers('following')
        
        if (this.page === 1) {
          this.followingList = mockUsers
        } else {
          this.followingList.push(...mockUsers)
        }
        
        this.hasMore = mockUsers.length === this.pageSize
      } catch (error) {
        console.error('加载关注列表失败:', error)
        this.showToast('加载失败，请重试', 'error')
      } finally {
        this.loading = false
      }
    },
    
    // 加载粉丝列表
    async loadFollowers() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        // 这里应该调用API获取粉丝列表
        // const res = await this.$api.getFollowers({
        //   uid: this.uid,
        //   page: this.page,
        //   pageSize: this.pageSize
        // })
        
        // 模拟数据
        const mockUsers = this.generateMockUsers('followers')
        
        if (this.page === 1) {
          this.followersList = mockUsers
        } else {
          this.followersList.push(...mockUsers)
        }
        
        this.hasMore = mockUsers.length === this.pageSize
      } catch (error) {
        console.error('加载粉丝列表失败:', error)
        this.showToast('加载失败，请重试', 'error')
      } finally {
        this.loading = false
      }
    },
    
    // 生成模拟用户数据
    generateMockUsers(type) {
      const users = []
      const usernames = ['小明', '小红', '小李', '小王', '小张', '小陈', '小刘', '小赵', '小孙', '小周']
      const descriptions = [
        '热爱生活，喜欢摄影',
        '旅行爱好者',
        '美食探索家',
        '读书分享者',
        '运动达人',
        '音乐爱好者',
        '设计师',
        '程序员',
        '学生',
        '自由职业者'
      ]
      
      for (let i = 0; i < Math.min(this.pageSize, 10); i++) {
        const user = {
          uid: Date.now() + i,
          username: usernames[i % usernames.length] + (1000 + i),
          avatar: `https://cdn.uviewui.com/uview/album/${(i % 6) + 1}.jpg`,
          description: descriptions[i % descriptions.length],
          followersCount: Math.floor(Math.random() * 1000) + 50,
          postCount: Math.floor(Math.random() * 100) + 10,
          isFollowed: type === 'following' ? true : Math.random() > 0.5,
          isMutualFollow: Math.random() > 0.6
        }
        users.push(user)
      }
      
      return users
    },
    
    // 获取当前列表
    getCurrentList() {
      return this.currentTab === 'following' ? this.followingList : this.followersList
    },
    
    // 获取空状态文本
    getEmptyText() {
      return this.currentTab === 'following' ? '还没有关注任何人' : '还没有粉丝'
    },
    
    // 下拉刷新
    async onRefresh() {
      this.refreshing = true
      this.page = 1
      await this.loadCurrentTabData()
      this.refreshing = false
    },
    
    // 加载更多
    async loadMore() {
      if (!this.hasMore) return
      
      this.page++
      await this.loadCurrentTabData()
    },
    
    // 事件处理方法
    handleUserProfile(user) {
      this.$tab.navigateTo(`/pages/user/profile?uid=${user.uid}`)
    },
    
    async handleFollow(user) {
      try {
        // 这里应该调用API关注用户
        user.isFollowed = true
        user.followersCount++
        
        // 如果是在粉丝列表中关注，需要检查是否互相关注
        if (this.currentTab === 'followers') {
          // 检查用户是否也关注了我
          user.isMutualFollow = Math.random() > 0.5
        }
        
        this.showToast('关注成功', 'success')
      } catch (error) {
        this.showToast('关注失败，请重试', 'error')
      }
    },
    
    async handleUnfollow(user) {
      try {
        const res = await uni.showModal({
          title: '确认取消关注',
          content: `确定要取消关注"${user.username}"吗？`
        })
        
        if (res.confirm) {
          // 这里应该调用API取消关注
          user.isFollowed = false
          user.isMutualFollow = false
          user.followersCount--
          
          // 如果是在关注列表中取消关注，需要从列表中移除
          if (this.currentTab === 'following') {
            const index = this.followingList.findIndex(item => item.uid === user.uid)
            if (index > -1) {
              this.followingList.splice(index, 1)
              this.followingCount--
            }
          }
          
          this.showToast('已取消关注', 'success')
        }
      } catch (error) {
        this.showToast('操作失败，请重试', 'error')
      }
    },
    
    showToast(title, type = 'default') {
      // 使用 uView 2.0 的 toast 方法
      this.$u.toast(title)
    }
  }
}
</script>

<style lang="scss" scoped>
.following-container {
  min-height: 100vh;
  background: #f8f9fa;
}

.tab-navigation {
  display: flex;
  background: white;
  margin-bottom: 10px;
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 15px 0;
    position: relative;
    
    &.active {
      .tab-text {
        color: #667eea;
        font-weight: 600;
      }
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 3px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 2px;
      }
    }
    
    .tab-text {
      font-size: 14px;
      color: #999;
    }
  }
}

.content-area {
  height: calc(100vh - 100px);
  padding: 0 15px;
}

.user-list {
  .user-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px;
    margin-bottom: 10px;
    
    .user-info {
      display: flex;
      align-items: center;
      flex: 1;
      
      .user-avatar {
        margin-right: 12px;
      }
      
      .user-details {
        flex: 1;
        
        .username {
          font-size: 15px;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 4px;
        }
        
        .user-desc {
          font-size: 13px;
          color: #666;
          margin-bottom: 6px;
          display: block;
        }
        
        .user-stats {
          display: flex;
          gap: 15px;
          
          .stat-text {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
    
    .user-actions {
      margin-left: 10px;
    }
  }
}

.load-more {
  text-align: center;
  padding: 20px;
  
  .load-text {
    font-size: 14px;
    color: #999;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  
  .empty-text {
    font-size: 16px;
    color: #999;
    margin-top: 20px;
    display: block;
  }
}
</style>